package com.imay.cocos;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.alibaba.fastjson.JSON;
import com.imay.base.util.StringUtil;
import com.imay.cocos.model.CocosClickModel;
import com.imay.cocos.model.CocosDataModel;
import com.imay.cocos.model.CocosImgDataModel;
import com.imay.cocos.model.CocosKeyboardModel;
import com.imay.cocos.model.CocosRoomHouseModel;
import com.imay.cocos.model.CocosStatusModel;
import com.imay.cocos.model.CocosTypeModel;
import com.imay.cocos.model.CocosUserInfoModel;
import com.imay.live.BuildConfig;
import com.imay.live.IMApplication;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.helper.ValueCallback;
import com.imay.live.manager.AccountManager;
import com.imay.live.model.CocosGetImgModel;
import com.imay.live.model.CocosStateModel;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.update.AppUpdateModel;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.GlideUtil;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.cocos2dx.lib.Cocos2dxLuaJavaBridge;
import org.cocos2dx.lib.ResizeLayout;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Random;

/**
 * Created by hexiao on 2017/4/12.
 */

public class IMayCocos {
    private static Object mEnterRoomData;   //房间数据，cocos可能无法接收到数据，需要重新拿数据
    //    public UIView* m_eglView;
    public int mhandler_event = 0;
    public int mhandler_network = 0;
    public int mhandler_network_notify = 0;
    private static IMayCocos mInstance;
    private AppUpdateModel appUpdateModel;
    public ResizeLayout m_eglFrameView;
    int orgParentViewCode = 0;//记住上次父类控件，不一致就说明需要执行下一步
    ArrayList<OnCocosUpdateListener> onCocosUpdateListeners = new ArrayList<OnCocosUpdateListener>();



    public IMayCocos() {

    }

    public static IMayCocos getInstance() {
        if (mInstance == null)
            mInstance = new IMayCocos();
        return mInstance;
    }

    public void addOnCocosUpdateListener(OnCocosUpdateListener onCocosUpdateListener) {
        if (onCocosUpdateListener != null) {
            onCocosUpdateListeners.add(onCocosUpdateListener);
            onCocosUpdateListener.onCocosAllowAction(IMayCocosNetManager.getInstance().getLauncherState());
        }
    }

    public void removeOnCocosUpdateListener(OnCocosUpdateListener onCocosUpdateListener) {
        if (onCocosUpdateListener != null) {
            onCocosUpdateListeners.remove(onCocosUpdateListener);
        }
    }

    public interface OnCocosUpdateListener {
        void onCocosAllowAction(int state);
    }


    public void onPause() {
//        applicationDidEnterBackground();
        Cocos2dxActivity.getInstance().onPause();
    }

    public void onResume() {
//        applicationWillEnterForeground();
        Cocos2dxActivity.getInstance().onResume();
    }

    //进入的时候创建cocos层
    public FrameLayout createCocosView() {
//        setContentView( IMayCocos.getInstance().getGLViewFrameLayout() );
        m_eglFrameView = Cocos2dxActivity.getInstance().onCreateCocosFrame(IMApplication.getInstance().getApplicationContext());

        IMayCocosNetManager.getInstance().setUpdateListener(new IMayCocosNetManager.OnCocosUpdateListener() {
            @Override
            public void onCocosShowAction(String jsonData) {//{"data":{"state":1},"id":"launcherState"}

                try {
                    CocosStateModel cocosStateModel = JSON.parseObject(jsonData, CocosStateModel.class);
                    int state = cocosStateModel.getState();
                    PreferenceHelper.getInstance().putString(PreferenceHelper.COCOSVERSONE, cocosStateModel.getVersion());
                    PreferenceHelper.getInstance().putString(PreferenceHelper.COCOSVCORE, cocosStateModel.getCore());
//                    if (IMayCocosNetManager.getInstance().getLauncherState() == 4) {
//                        //APK更新，所以不理会
//                    } else {
                    if (onCocosUpdateListeners != null) {
                        for (OnCocosUpdateListener onCocosUpdateListener : onCocosUpdateListeners) {
                            onCocosUpdateListener.onCocosAllowAction(state);
                        }
                    }
                    IMayCocosNetManager.getInstance().setLauncherState(state);
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onAppUpdateAction(String jsonData) {
//                {"versionId":"7.8.5","title":"1","url":"https://iosapp.imay.cn/imay_live.apk","desc2":"2","desc1":"1"}
                try {
                    appUpdateModel = JSON.parseObject(jsonData, AppUpdateModel.class);
                    EventHelper.postUpdateOnclice();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCocosGetImgAction(String jsonData) {
                try {
                    final CocosGetImgModel cocosGetImgModel = JSON.parseObject(jsonData, CocosGetImgModel.class);
                    GlideUtil.downloadImage(IMApplication.getInstance(), cocosGetImgModel.getUrl(), cocosGetImgModel.getWidth(), cocosGetImgModel.getHeight(), new ValueCallback<File>() {
                        @Override
                        public void onReceiveValue(File value) {
                            setCocosImgPath(cocosGetImgModel.getUrl(), value.getAbsolutePath());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return m_eglFrameView;
    }

    public Cocos2dxGLSurfaceView getGLView() {
        return Cocos2dxActivity.getInstance().getGLSurfaceView();
    }

    public AppUpdateModel getAppUpdateModel() {
        return appUpdateModel;
    }

    public void setAppUpdateModel(AppUpdateModel appUpdateModel) {
        this.appUpdateModel = appUpdateModel;
    }

    //cocos的framelayout,
    public FrameLayout getCocosView() {
        if (m_eglFrameView == null) {
            createCocosView();
        }

        return m_eglFrameView;
    }

    public void removeCocosViewParent() {
        ViewGroup parent = (ViewGroup) getCocosView().getParent();
        if (parent != null) {
            parent.removeView(m_eglFrameView);
        }
    }

    //lua调用显示和隐藏cocos层，之后交由原生控制
    public static void luaShowCocosView() {
        IMayCocos.getInstance().showCocosView();
    }

    public static void luaHideCocosView() {
        IMayCocos.getInstance().hideCocosView();
    }

    public void showCocosView() {
        getCocosView().setVisibility(View.GONE);
    }

    //隐藏cocosview，移出屏幕外
    public void hideCocosView() {
        getCocosView().setVisibility(View.GONE);
    }

    //pause resume
    public void cocosViewIsPause(boolean isPause) {
        if (isPause) {
//            CCDirector::sharedDirector()->pause();
        } else {
//            CCDirector::sharedDirector()->resume();
        }
    }

    //设置用户信息
    public static void setCocosUserInfo(long uid) {
        CocosUserInfoModel model = new CocosUserInfoModel();
        model.setUid(uid);
        sendCocosData(CocosValue.ID_SET_USER_INFO, model);
    }

    //主播端
    public static void enterRoomByPush(long roomId, String data) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_1);
        model.setUniId(roomId);
        model.setDt(data);
        enterRoom(model);
    }

    //观众端
    public static void enterRoomByLive(long roomId, String data) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_2);
        model.setUniId(roomId);
        model.setDt(data);
        enterRoom(model);
    }

    //游戏直播观众端
    public static void enterRoomByGame(long roomId, String data) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_4);
        model.setUniId(roomId);
        model.setDt(data);
        enterRoom(model);
    }

    //观众超胆播
    public static void enterRoomByShortLive(long roomId, String data) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_5);
        model.setUniId(roomId);
        model.setDt(data);
        enterRoom(model);
    }

    //超胆播主播端
    public static void enterRoomByShortLivePush(long roomId, String data) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_6);
        model.setUniId(roomId);
        model.setDt(data);
        enterRoom(model);
    }

    //手游直播切换横竖屏
    public static void swithGameLiveScreen(int type) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(type);
        sendCocosData(CocosValue.ID_SET_FULL_SCREEN, model);
    }

    //主播端
    public static void exitRoomByPush(long roomId) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_1);
        model.setUniId(roomId);
        exitRoom(model);
    }

    //观众端
    public static void exitRoomByLive(long roomId) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_2);
        model.setUniId(roomId);
        exitRoom(model);
    }

    //游戏直播观众端
    public static void exitRoomByGame(long roomId) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_4);
        model.setUniId(roomId);
        exitRoom(model);
    }

    //观众超胆播
    public static void exitRoomByShortLive(long roomId) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_5);
        model.setUniId(roomId);
        exitRoom(model);
    }

    //超胆播主播端
    public static void exitRoomByShortLivePush(long roomId) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_ENTER_6);
        model.setUniId(roomId);
        exitRoom(model);
    }

    //退出房间
    private static void exitRoom(Object data) {
        mEnterRoomData = data;
        sendCocosData(CocosValue.ID_SET_EXIT_ROOM, data);
    }

    //通知cocos进入房间
    private static void enterRoom(Object data) {
        mEnterRoomData = data;
        //测试，每次进入都设置一次uid
        setCocosUserInfo(AccountManager.getInstance().getUid());

        sendCocosData(CocosValue.ID_SET_ENTER_ROOM, data);
    }

    //显示cocos礼物面板
    public static void showGiftPanel(UserInfoCard user) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_GIFT);
        model.setDt(user);
        model.setSenderType(1); //主播
        showCocosUI(model);
    }

    //显示cocos礼物面板(观众)
    public static void showGiftPanel() {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_GIFT);
        model.setSenderType(2); //观众
        showCocosUI(model);
    }

    //显示cocos游戏面板
    public static void showGamePanel() {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_GAME);
        showCocosUI(model);
    }

    //显示商场面板
    public static void showMarketPanel(Integer mountId) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_MARKET);
        model.setMountId(mountId);
        showCocosUI(model);
    }

    //商场退出登录
    public static void logout() {
        sendCocosData(CocosValue.ID_SET_LOGOUT, null);
    }

    //关闭商城面板
    public static void closeMarketPannel() {
        sendCocosData(CocosValue.ID_SET_CLOSE_SHOP_UI, null);
    }

    private static void showCocosUI(Object object) {
        sendCocosData(CocosValue.ID_SET_SHOW_COCOS, object);
    }

    //点击游戏隐藏按钮
    public static void setGameStatus() {
        sendCocosData(CocosValue.ID_SET_GAME_STATUS);
    }

    //设置点击区域
    public static void setClickBound(int id, View view) {
        int[] outLocation = new int[2];
        view.getLocationInWindow(outLocation);
        CocosClickModel.ClickModel clickModel = new CocosClickModel.ClickModel();
        clickModel.setX(outLocation[0]);
        clickModel.setY(outLocation[1]);
        clickModel.setW(view.getMeasuredWidth());
        clickModel.setH(view.getMeasuredHeight());

        CocosClickModel cocosClickModel = new CocosClickModel();
        cocosClickModel.setKey(id);
        cocosClickModel.setDt(clickModel);

        sendCocosData(CocosValue.ID_SET_CLICK_BOUND, cocosClickModel);
    }

    //关闭点击事件
    public static void closeClickBound(int id) {
        CocosClickModel cocosClickModel = new CocosClickModel();
        cocosClickModel.setKey(id);
        sendCocosData(CocosValue.ID_SET_CLOSE_CLICK_BOUND, cocosClickModel);
    }

    //重新设置房间数据
    public static void reTryEnterRoom() {
        if (mEnterRoomData != null) {
            enterRoom(mEnterRoomData);
        }
    }

    //通知cocos隐藏房间UI
    public static void setRoomSimpleMode(boolean simple) {
        CocosStatusModel model = new CocosStatusModel();
        model.setStatus(simple ? CocosValue.STATUS_VIEW_HIDE : CocosValue.STATUS_VIEW_SHOW);
        sendCocosData(CocosValue.ID_SET_IS_SHOW_UI, model);
    }

    //设置键盘状态
    public static void setKeyboardStatus(boolean show, int width, int height) {
        CocosKeyboardModel model = new CocosKeyboardModel();
        model.setStatus(show ? CocosValue.STATUS_KEYBOARD_SHOW : CocosValue.STATUS_KEYBOARD_CLOSE);
        model.setHeight(height);
        model.setWidth(width);
        sendCocosData(CocosValue.ID_SET_KEYBOARD_STATUS, model);
    }

    // 通知本地图片
    public static void setCocosImgPath(String url, String path) {
        CocosImgDataModel model = new CocosImgDataModel();
        model.setUrl(url);
        model.setPath(path);
        sendCocosData(CocosValue.ID_SET_GET_IMAGE, model);
    }

    //显示超胆播点赞按钮
    public static void showShortLiveLike() {
        sendCocosData(CocosValue.ID_SET_SHORT_LIVE_LIKE, null);
    }

    //显示超胆播挑战完成动画
    public static void showShortLiveEnd() {
        sendCocosData(CocosValue.ID_SET_SHORT_LIVE_END, null);
    }

    //显示超胆播倒计时转圈
    public static void showShortLiveCountDown(int speed) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_COUNT_DOWN);
        model.setSpeed(speed);
        showCocosUI(model);
    }

    //显示大富婆建楼卡
    public  void showHouseCard(int rData, int userLv) {
        CocosTypeModel model = new CocosTypeModel();
        model.setmType(CocosValue.TYPE_ROOM_HOUSE);
        CocosRoomHouseModel houseModel = new CocosRoomHouseModel();
        houseModel.setrData(rData);
        houseModel.setUserLv(userLv);
        model.setDt(houseModel);
        showCocosUI(model);
    }

    //关闭所有ui特效，包括猴子
    public static void closeAllEffect() {
        sendCocosData(CocosValue.ID_SET_CLOSE_ALL_EFFECT, null);
    }

    private static void sendCocosData(String id) {
        CocosDataModel model = new CocosDataModel();
        model.setId(id);
        IMayCocos.SDK2Cocos(JSON.toJSONString(model));
    }

    private static void sendCocosData(String id, Object data) {
        CocosDataModel model = new CocosDataModel();
        model.setId(id);
        model.setData(data);
        IMayCocos.SDK2Cocos(JSON.toJSONString(model));
    }

    //关闭建楼卡
    public static void closeRoomHouse() {
        sendCocosData(CocosValue.ID_SET_CLOSE_HOUSE, null);
    }

    public static int resgiterSDKCocosHandler(int handle1, int handle2, int handle3) {
        IMayCocos.getInstance().setHandler(handle1, handle2, handle3);
        return 1;
    }

    public void releaseHandler() {
        if (mhandler_event != 0) {
            Cocos2dxLuaJavaBridge.releaseLuaFunction(mhandler_event);
            mhandler_event = 0;
        }
        if (mhandler_network != 0) {
            Cocos2dxLuaJavaBridge.releaseLuaFunction(mhandler_network);
            mhandler_network = 0;
        }
        if (mhandler_network_notify != 0) {
            Cocos2dxLuaJavaBridge.releaseLuaFunction(mhandler_network_notify);
            mhandler_network_notify = 0;
        }
    }

    public void setHandler(int eventHandler, int networkHandler, int networkNotifyHandler) {
        this.releaseHandler();
        mhandler_event = eventHandler;
        mhandler_network = networkHandler;
        mhandler_network_notify = networkNotifyHandler;
        Cocos2dxLuaJavaBridge.retainLuaFunction(mhandler_event);
        Cocos2dxLuaJavaBridge.retainLuaFunction(mhandler_network);
        Cocos2dxLuaJavaBridge.retainLuaFunction(mhandler_network_notify);
    }

    //cocos 通知 原生
    public static int Cocos2SDK_event(String jsonData)            //一般ui切换事件
    {
        Log.i("Cocos2SDK_event", jsonData);
        //调用原生接口
        IMayCocosNetManager.getInstance().cocos2SDK_event(jsonData);
        return 1;

    }

    public static int Cocos2SDK_network(String jsonData)           //cocos通知原生发送网络数据事件
    {
        Log.i("Cocos2SDK_network", jsonData);
        //调用原生接口
        IMayCocosNetManager.getInstance().cocos2SDK_network(jsonData);
        return 1;
    }

    public static String Cocos2SDK_getIdentifier()           //cocos通知原生获取设备唯一标识符
    {

        String imei = null;
        try {
            imei = ((TelephonyManager) IMApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE))
                    .getDeviceId();
        } catch (Exception e) {
        }
        return !StringUtil.isEmpty(imei) ? imei : System.currentTimeMillis() + "_AVanka_" + new Random().nextInt(1000);

    }

    public static String Cocos2SDK_getVersionName()           //cocos通知原生获取版本号
    {
        return BuildConfig.VERSION_NAME;
    }

    public static String Cocos2SDK_getChannelId()           //cocos通知原生获取渠道号
    {
        return AppUtil.getChannel(IMApplication.getInstance());
    }

    public static int getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = Cocos2dxActivity.getInstance().getContext().getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (AppUtil.isLowVersion()) {
            return 0;
        }
        return sbar;
    }

    //原生 通知 cocos
    public static int SDK2Cocos(final String jsonData)                    //一般ui切换事件
    {
        Log.i("SDK2Cocos_event", jsonData);
        IMayCocos.getInstance().callLuaData_event(jsonData);
        return 1;
    }

    public static int SDK2Cocos_network(int msgId, final String jsonData)                    //发送数据返回事件
    {
        if (jsonData != null) {
            IMayCocos.getInstance().callLuaData_network(msgId, jsonData);
            Log.i("SDK2Cocos", jsonData);
        }
        return 1;
    }

    public static int SDK2Cocos_network_Notify(int msgId, String jsonData)                    //网络主动通知事件
    {
        Log.i("SDK2Cocos", jsonData);
        IMayCocos.getInstance().callLuaData_network_notify(msgId, jsonData);
        return 1;
    }

    //回调lua接口
    public int callLuaData_event(final String jsonData)           //一般ui事件回调
    {
        if (mhandler_event != 0) {
            pushEventData(jsonData);
        }
        return 1;
    }

    public int callLuaData_network(int msgId, final String jsonData)          //发送数据返回回调
    {
        if (mhandler_network != 0) {
            pushNetworkData(jsonData, msgId);
        }
        return 1;
    }

    public int callLuaData_network_notify(int msgId, final String jsonData)           //网络主动通知事件回调
    {
        if (mhandler_network_notify != 0) {
            pushNwNotifyData(jsonData, msgId);
        }
        return 1;
    }

    public static int isDebug() {
        if (BuildConfig.IS_RELEASE && !BuildConfig.DEBUG) {
            return 0;
        }
        return 2;
    }

    public static String getServerHost() {
        return UrlHelper.getServerHost();
    }

    private static native void pushEventData(String jsonData);

    private static native void pushNetworkData(String jsonData, int msgId);

    private static native void pushNwNotifyData(String jsonData, int msgId);

    private static native void applicationDidEnterBackground();

    private static native void applicationWillEnterForeground();

    public static String getAuthParams()
    {
        return ProtoHttpFactory.getAuthParams();
    }

    public static String getAuthParamsAsJson()
    {
        return ProtoHttpFactory.getAuthParamsAsJson();
    }

    public static String isRelease()
    {
        if(BuildConfig.IS_RELEASE)
            return "true";
        else
            return "false";
    }

}
